$.datepicker.setDefaults({
	dateFormat: 'dd/mm/yy'
});

jQuery.fn.forceDouble = function () {

	return this.each(function () {
		$(this).keydown(function (e) {
			var key = e.which || e.keyCode;
			
			if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
					// numbers   
					(key >= 48 && key <= 57) ||
					// Numeric keypad
					(key >= 96 && key <= 105) ||
					// period and comma
					(key == 190 || key == 110 || key == 188) ||
					// Backspace and Tab and Enter
					key == 8 || key == 9 || key == 13 ||
					// Home and End
					key == 35 || key == 36 ||
					// left and right arrows
					key == 37 || key == 39 ||
					// Del and Ins
					key == 46 || key == 45) {		                     
				return true;
			}
			else if(e.shiftKey){
				return (key >= 48 && key <= 57);
			}

			return false;
		});
	});
}


jQuery.fn.forceInteger = function () {

	return this.each(function () {
		$(this).keydown(function (e) {
			var key = e.which || e.keyCode;


			if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
					// numbers   
					(key >= 48 && key <= 57) ||
					// Numeric keypad
					(key >= 96 && key <= 105) ||
					// Backspace and Tab and Enter
					key == 8 || key == 9 || key == 13 ||
					// Home and End
					key == 35 || key == 36 ||
					// left and right arrows
					key == 37 || key == 39 ||
					// Del and Ins
					key == 46 || key == 45) {		                     
				return true;
			}
			else if(e.shiftKey){
				return (key >= 48 && key <= 57);
			}

			return false;
		});
	});
}

jQuery.fn.saveValueAfterChange = function (history, originalValues) {
	
	return this.each(function () {				
		$(this).change(function (e) {	
			
			var value;
			//add the change to the list
			if($(e.target).attr('type') == 'checkbox')								
				value = $(e.target).is(':checked');
			else
				value = e.target.value;
			
			history.addChange($(e.target), originalValues[e.target.name], value, true);
			
			//if this field is a reference (it ends with Id), its probably an autocomplete,
			//in this case I have to change the description field as well
			if(isReferenceField(e.target)) {				
				var descField = $('#'+e.target.name.substr(0, e.target.name.length-2));				
				history.addChange(descField, originalValues[descField.attr('name')], descField.val(), false);	
			}
			
			jQuery.ajax({
				url: 'generalAjaxServlet?action=saveField&entity='+$('#entity').val()+'&field='+e.target.name+'&value='+value+'&id='+$('#id').val(),
				context: e.target,
				success: function(data) {
					if(data == 'error') {
						$(this).addClass('fieldError');
					}
					else
						$(this).removeClass('fieldError');
				},
				error: function() {
					$(this).addClass('fieldError');
				}
			});
			
			return true;
		});
	});
}


function isReferenceField(field) {
	
	return field.name.lastIndexOf('Id') > 0 && (field.name.lastIndexOf('Id') == field.name.length-2);
}

function undoChanges(history) {
	var params = '';
	var count = 0;
	
	//is it an existing entity?
	if($('#new').val() != 1) {
		for(i=0;i<history.changes.length;i++) {		
			history.changes[i].undo();
			if(history.changes[i].doUpdate) {			
				params += '&field' + count + '=' + history.changes[i].element.attr('name') + '&value' + count + '=' + history.changes[i].oldValue;
				count++;
			}
		}
		
		//only undo if there were changes
		if(count > 0) {
			params = '&count=' + count + '&entity=' + $('#entity').val() + '&id=' + $('#id').val() + params;
			
			
			//make an ajax call to persist the changes
			jQuery.ajax({
				url: 'generalAjaxServlet?action=saveMultipleFields'+params,
				async: false
			});
		}
	}
	else {
		
		//make an ajax call to delete the changes
		jQuery.ajax({
			url: 'generalEditor?entity='+$('#entity').val()+'&action=delete&id='+$('#id').val(),
			async: false
		});
		
	}
	
}

function loadOriginalValues(originalValues) {
	
	$('#formMain :input').each(function() {
		if($(this).attr('type') == 'checkbox')
			addOriginalValue(originalValues, this.name, $(this).is(':checked'));			
		else
			addOriginalValue(originalValues, this.name, $(this).val());
	});
	
}

function addOriginalValue(originalValues, fieldName, value) {
	originalValues[fieldName] = value;
}

/*******************************************************/
//history object
function History() {
	this.changes = new Array(); 
	this.addChange = addChange;
}

function addChange(element, oldValue, newValue, doUpdate) {
	var found = false;
	//check if that field was already changed
	for(i=0;i<this.changes.length;i++) {
		if(this.changes[i].element == element) {
			found = true;
			this.changes[i].newValue = newValue;
		}
			
	}
	if(!found)
		this.changes[this.changes.length] = new Change(element, oldValue, newValue, doUpdate);
	
}
/*******************************************************/
//change object
function Change(element, oldValue, newValue, doUpdate) {
	this.element = element;
	this.oldValue = oldValue;
	this.newValue = newValue;
	this.doUpdate = doUpdate;
	this.undo = undo;
}

function undo() {
	if(this.element.attr('type') == 'checkbox')
		this.element.prop('checked', this.oldValue);
	else
		this.element.val(this.oldValue);
	
}
/*******************************************************/


function makeNavigatorCrud(listName, pagerName, newHref, width, height, entityName, editHref, onClose) {

	//this is an optional parameter
	if(!editHref)
		editHref = 'generalEditor';
	
	jQuery('#'+listName).jqGrid('navGrid','#'+pagerName, 
			{	addfunc: function(){
							$.colorbox({iframe:true, 
										href:newHref, 
										width:width, 
										height:height, 
										overlayClose:false,
										opacity: 0.2,
										onClosed: function() {
														jQuery('#'+listName).trigger("reloadGrid");
														if(onClose != null)
															onClose();
													}
										});
	  					},
	  			editfunc: 	function(id) {
				  				if(id) {
				  					$.colorbox({iframe:true, 
										href:editHref+'?entity='+entityName+'&id='+id, 
										width:width, 
										height:height, 
										overlayClose:false,
										opacity: 0.2,
										onClosed: function() {
														jQuery('#'+listName).trigger("reloadGrid");
														if(onClose != null)
															onClose();
													}
										});
				  				}
				  				
	  						},
	  			delfunc:	function(id) {
	  				  			if(id) {
		  				  			if(confirm('delete?')) {
		  								jQuery.ajax({	url: 'generalEditor?entity='+entityName+'&action=delete&id='+id,
		  												success: function(data){
		  													jQuery('#'+listName).trigger("reloadGrid");
		  													
		  													// show possible feedback messages
															showFeedbackMessages(data, 'feedbackContainer');
		  								  				}
		  										});
		  							}
	  				  			}
	  						},
	  		 	edit:true,
	  			add:true,
	  			del:true,
	  			search:false
	  		}, 
			{}, 
			{}, 
			{}, 
			{} );	
	
	//if its a new entity, dont allow to add new children
	if($('#id').val() == '') {
		$("#add_" + jQuery('#'+listName)[0].id).addClass('ui-state-disabled');
		$("#edit_" + jQuery('#'+listName)[0].id).addClass('ui-state-disabled');
		$("#del_" + jQuery('#'+listName)[0].id).addClass('ui-state-disabled');
	}
}


function makeEnumSelector(selectName, enumName, selectedValue) {
	makeEnumSelector(selectName, enumName, selectedValue, true);
}

function makeEnumSelector(selectName, enumName, selectedValue, sort) {
	makeEnumSelector(selectName, enumName, selectedValue, sort, false);
}

function makeEnumSelector(selectName, enumName, selectedValue, sort, addChooseOne) {
	jQuery.ajax({											
		url: 'generalAjaxServlet?action=getEnumForSelect&enum='+enumName+'&sort='+sort,
		dataType: 'json',
		success: function(data) {
			
					fillDropDown(data, selectName, selectedValue, addChooseOne);
				}										
	});
}

function makeDropDownSelector(selectName, entityName, selectedValue, addChooseOne) {
	jQuery.ajax({											
		url: 'cliente?action=getOptionsForSelect&entity='+entityName,
		dataType: 'json',
		success: function(data) {			
					fillDropDown(data, selectName, selectedValue, addChooseOne);
				}										
	});
}


function fillDropDown(data, selectName, selectedValue, addChooseOne) {
	
	// clear possible previous values
	$('#'+selectName).empty();
	
	if(addChooseOne) {
		$('#'+selectName).append('<option value="null" '+ (selectedValue == "" ? "selected" : "") +'>Choose One</option>');
	}
	
	for(var key in data){
		var selected = '';
		if(data[key].value == selectedValue)
			selected = 'selected';
		
		$('#'+selectName).append('<option value="'+data[key].value+'" '+selected+'>'+data[key].label+'</option>');
	}
	
}

function populateSelector(selectName, url, selectedValue, addChooseOne) {
	jQuery.ajax({											
		url: url,
		dataType: 'json',
		success: function(data) {
			fillDropDown(data, selectName, selectedValue, addChooseOne);																	
		}										
	});
}

// in case they exist, show the feedback messages (used to show ajax feedback)
function showFeedbackMessages(data, feedbackContainerId) {
	
	$('#feedbackList').remove();
	
	if(containsFeedbackMessage(data)) {
		$('#'+feedbackContainerId).append('<ul id="feedbackList"></ul>');
		for(var key in data){																				
			$('#feedbackList').append('<li>'+data[key].message+'</li>');
		}
		
		$('#'+feedbackContainerId).show();
	}
	else {
		$('#'+feedbackContainerId).hide();
	}
}

// check if the json data object ontains any feedback message
function containsFeedbackMessage(data) {
	
	for(var key in data){
		if(key.indexOf("feedback")==0)
			return true;
	}
	
	return false;
}

function dateToStr(date) {
	var result = '';
	
	var arr = date.split(',');
	var month = arr[0].split(' ')[0];
	var day = arr[0].split(' ')[1];
	var year = arr[1].split(' ')[1];
	
	
	return day + '/' + monthNameToNumber(month) + '/' + year;
}

function monthNameToNumber(month) {
	var result = 0;
	
	if(month == 'Jan')
		result = 1;
	else if(month == 'Feb')
		result = 2;
	else if(month == 'Mar')
		result = 3;
	else if(month == 'Apr')
		result = 4;
	else if(month == 'May')
		result = 5;
	else if(month == 'Jun')
		result = 6;
	else if(month == 'Jul')
		result = 7;
	else if(month == 'Aug')
		result = 8;
	else if(month == 'Sep')
		result = 9;
	else if(month == 'Oct')
		result = 10;
	else if(month == 'Nov')
		result = 11;
	else if(month =='Dic')
		result = 12;
	
	return result;
}

// convert a given string representing a number to float 
function clearForCalculation(strValue) {
	return parseFloat(strValue.replace('.', '', 'g').replace(',', '.'));
}

function formatResult(num) {
	num = Math.round(num*100)/100; //multiply by 100 and round, then divide by 100 to get 2 decimals
	return num.toString().replace('.', ',');
}